package com.tbynet.jwp.admin.post;

import com.jfinal.aop.Inject;
import com.tbynet.jwp.admin.AdminController;
import com.tbynet.jwp.framework.kit.DateKit;
import com.tbynet.jwp.model.Posts;
import com.tbynet.jwp.model.Terms;
import com.tbynet.jwp.repository.spi.PostExportService;
import com.tbynet.jwp.repository.spi.TermService;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

/**
 * 文章导出控制器
 * @ClassName: PostExportController
 * @Description: 提供文章导出功能，支持CSV和XML格式
 * @Author: 佰亿互联
 * @Date: 2019年3月22日 下午3:05:05
 *
 * @Copyright: 2019 www.tbynet.com Inc. All rights reserved.
 * 注意: 本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */
public class PostExportController extends AdminController {

    @Inject
    private PostExportService postExportService;

    @Inject
    private TermService termService;

    /**
     * 导出文章为CSV格式
     * @throws IOException 当IO操作失败时抛出
     */
    public void csv() throws IOException {
        String status = getPara("status");
        String category = getPara("category");
        String dateFrom = getPara("date_from");
        String dateTo = getPara("date_to");

        try {
            // 设置响应头
            getResponse().setContentType("text/csv;charset=utf-8");
            getResponse().setHeader("Content-Disposition",
                    "attachment; filename=posts_" + DateKit.format(new java.util.Date(), "yyyyMMddHHmmss") + ".csv");

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(getResponse().getOutputStream(), "UTF-8"));

            // 写入CSV表头
            writer.write("ID,标题,内容,状态,作者,分类,标签,创建时间,修改时间,摘要");
            writer.newLine();

            // 查询文章数据
            List<Posts> posts = postExportService.getPostsForExport(status, category, dateFrom, dateTo);

            for (Posts post : posts) {
                // 获取分类和标签
                String categories = postExportService.getPostCategories(post.getID());
                String tags = postExportService.getPostTags(post.getID());

                // 构建CSV行
                String[] row = {
                        post.getID().toString(),
                        postExportService.escapeCsv(post.getPostTitle()),
                        postExportService.escapeCsv(post.getPostContent()),
                        post.getPostStatus(),
                        post.getPostAuthor().toString(),
                        postExportService.escapeCsv(categories),
                        postExportService.escapeCsv(tags),
                        DateKit.format(post.getPostDate(), "yyyy-MM-dd HH:mm:ss"),
                        DateKit.format(post.getPostModified(), "yyyy-MM-dd HH:mm:ss"),
                        postExportService.escapeCsv(post.getPostExcerpt())
                };

                writer.write(String.join(",", row));
                writer.newLine();
            }

            writer.flush();
            writer.close();

            renderNull();

        } catch (Exception e) {
            e.printStackTrace();
            renderError(500);
        }
    }

    /**
     * 导出文章为XML格式（WordPress兼容格式）
     * @throws IOException 当IO操作失败时抛出
     */
    public void xml() throws IOException {
        try {
            getResponse().setContentType("application/xml;charset=utf-8");
            getResponse().setHeader("Content-Disposition",
                    "attachment; filename=wordpress_export_" + DateKit.format(new java.util.Date(), "yyyyMMddHHmmss") + ".xml");

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(getResponse().getOutputStream(), "UTF-8"));

            // 写入XML头部
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            writer.newLine();
            writer.write("<rss version=\"2.0\" xmlns:excerpt=\"http://wordpress.org/export/1.2/excerpt/\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\" xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:wp=\"http://wordpress.org/export/1.2/\">");
            writer.newLine();
            writer.write("<channel>");
            writer.newLine();

            // 写入站点信息
            writer.write("<wp:wxr_version>1.2</wp:wxr_version>");
            writer.newLine();
            writer.write("<title>" + postExportService.escapeXml(postExportService.getSiteTitle()) + "</title>");
            writer.newLine();
            writer.write("<link>" + postExportService.getSiteUrl() + "</link>");
            writer.newLine();
            writer.write("<description>" + postExportService.escapeXml(postExportService.getSiteDescription()) + "</description>");
            writer.newLine();

            // 查询并写入文章
            List<Posts> posts = postExportService.getPostsForExport(null, null, null, null);
            for (Posts post : posts) {
                writePostToXml(writer, post);
            }

            writer.write("</channel>");
            writer.newLine();
            writer.write("</rss>");

            writer.flush();
            writer.close();

            renderNull();

        } catch (Exception e) {
            e.printStackTrace();
            renderError(500);
        }
    }

    /**
     * 将单篇文章写入XML格式
     * @param writer BufferedWriter对象
     * @param post 文章对象
     * @throws IOException 当IO操作失败时抛出
     */
    private void writePostToXml(BufferedWriter writer, Posts post) throws IOException {
        writer.write("<item>");
        writer.newLine();
        writer.write("<title>" + postExportService.escapeXml(post.getPostTitle()) + "</title>");
        writer.newLine();
        writer.write("<link>" + postExportService.getPostUrl(post) + "</link>");
        writer.newLine();
        writer.write("<pubDate>" + DateKit.format(post.getPostDate(), "EEE, dd MMM yyyy HH:mm:ss Z") + "</pubDate>");
        writer.newLine();
        writer.write("<dc:creator>" + postExportService.escapeXml(postExportService.getAuthorName(post.getPostAuthor())) + "</dc:creator>");
        writer.newLine();
        writer.write("<guid isPermaLink=\"false\">" + postExportService.getPostUrl(post) + "</guid>");
        writer.newLine();
        writer.write("<description></description>");
        writer.newLine();
        writer.write("<content:encoded><![CDATA[" + post.getPostContent() + "]]></content:encoded>");
        writer.newLine();
        writer.write("<excerpt:encoded><![CDATA[" + post.getPostExcerpt() + "]]></excerpt:encoded>");
        writer.newLine();
        writer.write("<wp:post_id>" + post.getID() + "</wp:post_id>");
        writer.newLine();
        writer.write("<wp:post_date>" + DateKit.format(post.getPostDate(), "yyyy-MM-dd HH:mm:ss") + "</wp:post_date>");
        writer.newLine();
        writer.write("<wp:post_date_gmt>" + DateKit.format(post.getPostDateGmt(), "yyyy-MM-dd HH:mm:ss") + "</wp:post_date_gmt>");
        writer.newLine();
        writer.write("<wp:post_modified>" + DateKit.format(post.getPostModified(), "yyyy-MM-dd HH:mm:ss") + "</wp:post_modified>");
        writer.newLine();
        writer.write("<wp:post_modified_gmt>" + DateKit.format(post.getPostModifiedGmt(), "yyyy-MM-dd HH:mm:ss") + "</wp:post_modified_gmt>");
        writer.newLine();
        writer.write("<wp:comment_status>" + post.getCommentStatus() + "</wp:comment_status>");
        writer.newLine();
        writer.write("<wp:ping_status>" + post.getPingStatus() + "</wp:ping_status>");
        writer.newLine();
        writer.write("<wp:post_name>" + post.getPostName() + "</wp:post_name>");
        writer.newLine();
        writer.write("<wp:status>" + post.getPostStatus() + "</wp:status>");
        writer.newLine();
        writer.write("<wp:post_parent>0</wp:post_parent>");
        writer.newLine();
        writer.write("<wp:menu_order>0</wp:menu_order>");
        writer.newLine();
        writer.write("<wp:post_type>post</wp:post_type>");
        writer.newLine();
        writer.write("<wp:post_password></wp:post_password>");
        writer.newLine();
        writer.write("<wp:is_sticky>0</wp:is_sticky>");
        writer.newLine();

        // 写入分类
        List<Terms> categories = termService.getTerms(post.getID(), "category");
        for (Terms category : categories) {
            writer.write("<category domain=\"category\" nicename=\"" + category.getStr("slug") + "\"><![CDATA[" + category.getStr("name") + "]]></category>");
            writer.newLine();
        }

        // 写入标签
        List<Terms> tags = termService.getTerms(post.getID(), "post_tag");
        for (Terms tag : tags) {
            writer.write("<category domain=\"post_tag\" nicename=\"" + tag.getStr("slug") + "\"><![CDATA[" + tag.getStr("name") + "]]></category>");
            writer.newLine();
        }

        writer.write("</item>");
        writer.newLine();
    }
}